package com.android.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import android.os.Environment;
import android.util.Log;

public class CompressUtils
{
	public static boolean zip(String location, String fileName, String destiny)
	{
		try
		{
			byte[] buffer = new byte[1024];
			
			FileOutputStream fos;
			fos = new FileOutputStream(destiny + File.separator + fileName + ".zip");
			ZipOutputStream zos = new ZipOutputStream(fos);
			ZipEntry ze = new ZipEntry(fileName);
			zos.putNextEntry(ze);
			FileInputStream in = new FileInputStream(location + fileName);
			
			int len;
			while ((len = in.read(buffer)) > 0)
			{
				zos.write(buffer, 0, len);
			}
			
			in.close();
			zos.closeEntry();
			
			zos.close();
		}
		catch (FileNotFoundException e)
		{
			Log.e("CompressUtils", e.getMessage());
			return false;
		}
		catch (IOException e)
		{
			Log.e("CompressUtils", e.getMessage());
			return false;
		}
		
		return true;
	}
	
	public static boolean unZip(String location, String fileName, String destiny)
	{
		byte[] buffer = new byte[1024];

		try
		{
			File folder = new File(destiny);

			if (!folder.exists())
			{
				folder.mkdir();
			}

			ZipInputStream zis = new ZipInputStream(new FileInputStream(location));
			ZipEntry ze = zis.getNextEntry();

			while (ze != null)
			{

				File newFile = new File(destiny + File.separator + fileName);

				new File(newFile.getParent()).mkdirs();

				FileOutputStream fos = new FileOutputStream(newFile);

				int len;
				while ((len = zis.read(buffer)) > 0)
				{
					fos.write(buffer, 0, len);
				}

				fos.close();
				ze = zis.getNextEntry();
			}

			zis.closeEntry();
			zis.close();

		}
		catch (IOException ex)
		{
			Log.e("CompressUtils", ex.getMessage());
			return false;
		}

		return true;
	}
	
	public static void copyFile(String location, String destiny)
	{
		try
		{
			File sd = Environment.getExternalStorageDirectory();
			if (sd.canWrite())
			{
				File currentDB = new File(location);
				File newBD = new File(destiny);

				FileChannel src = new FileInputStream(currentDB).getChannel();
				FileChannel dst = new FileOutputStream(newBD).getChannel();

				dst.transferFrom(src, 0, src.size());
				src.close();
				dst.close();
			}
		}
		catch (Exception e)
		{
			Log.e("CompressUtils", e.getMessage());
		}
	}
}
